#!/bin/bash

function show_usage() {
    printf "usage: %s [ -d ] tracroot_dir destination_dir\n" \
        $( basename $0 ) >&2
    echo "(try the -d option if trac-admin complains about mkdir)"
}

CREATE_DESTINATION=1
while getopts 'd' OPTION
do
    case $OPTION in
        d) CREATE_DESTINATION=0;;
        ?) show_usage
           exit 1
           ;;
    esac
done
shift $((OPTIND - 1))

TRAC_ROOT=$1
if [ -z $TRAC_ROOT ]; then
    show_usage
    exit 2
fi
if [ ! -d $TRAC_ROOT ]; then
    echo "directory '$TRAC_ROOT' does not exist"
    exit 4
fi
TRAC_BAC_ROOT=$2
if [ -z $TRAC_BAC_ROOT ]; then
    show_usage
    exit 2
fi

TODAY=$( date +%Y%m%d%H%M%S )
if [ $CREATE_DESTINATION -eq 1 ]; then
    mkdir -p $TRAC_BAC_ROOT/$TODAY
fi

for i in $TRAC_ROOT/*
do
    DEST=$TRAC_BAC_ROOT/$TODAY/$( basename $i )
    DEST_TARGZ=${DEST}.tar.gz
    trac-admin $i hotcopy $DEST
    tar czf $DEST_TARGZ $DEST
    rm -rf $DEST
done

SYMLINK="$TRAC_BAC_ROOT/current"
rm -f $SYMLINK
ln -s $TODAY $SYMLINK
